package tongcheng.com.tongcheng.ui.yemian.shenfen.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.yanzhenjie.nohttp.RequestMethod;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import tongcheng.com.tongcheng.ConStans;
import tongcheng.com.tongcheng.R;
import tongcheng.com.tongcheng.base.BaseActivity;
import tongcheng.com.tongcheng.network.CallServer;
import tongcheng.com.tongcheng.network.MyRequest;
import tongcheng.com.tongcheng.network.OnCallBack;
import tongcheng.com.tongcheng.ui.yemian.mapui.DaiLiQiangDanActivity;
import tongcheng.com.tongcheng.ui.yemian.mapui.GeRenFaDanActivity;
import tongcheng.com.tongcheng.ui.yemian.mapui.InstallQiangDanActivity;
import tongcheng.com.tongcheng.ui.yemian.mapui.OnePersonQiangDanActivity;
import tongcheng.com.tongcheng.utils.AndroidBug54971Workaround;
import tongcheng.com.tongcheng.utils.Setting;
import tongcheng.com.tongcheng.utils.ShowToast;
import tongcheng.com.tongcheng.zhifubao.PayResult;

import static tongcheng.com.tongcheng.utils.Setting.getShenfen;

public class BaoZhenJinActivity extends BaseActivity {

    @Bind(R.id.back)
    ImageView mBack;
    @Bind(R.id.title)
    TextView mTitle;
    // @Bind(R.id.bg)
    RelativeLayout mBg;
    @Bind(R.id.baozhen_ll1)
    LinearLayout mBaozhenLl1;
    @Bind(R.id.baozhen_ok)
    Button mBaozhenOk;
    @Bind(R.id.back_text)
    TextView mBackText;
    @Bind(R.id.baozhen_weixin)
    RadioButton mBaozhenWeixin;
    @Bind(R.id.baozhen_zhifubao)
    RadioButton mBaozhenZhifubao;
    @Bind(R.id.bt_tiaoGuo)
    Button bt_tiaoGuo;
    @Bind(R.id.tv_baoZhengJin)
    TextView tv_baoZhengJin;
    public int temp = 0;

    public static BaoZhenJinActivity baozhenInstance;
    @Override
    public Integer initResid() {
        return R.layout.activity_bao_zhen_jin;
    }

    @Override
    public void initCreate(Bundle savedInstanceState) {
        baozhenInstance = this;
            AndroidBug54971Workaround.assistActivity(findViewById(R.id.allmain));
        mBg = (RelativeLayout) findViewById(R.id.title_bar);
        mBg.setBackgroundColor(0xffffea00);
        settitlebar(mBg);
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        mTitle.setText("缴纳保证金");

        getPeiZhiXinXi();

        bt_tiaoGuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (getShenfen()) {
                    case 1://企业
                        startactivity(BaoZhenJinActivity.this, GeRenFaDanActivity.class);
                        break;
                    case 2://个人发单
                        startactivity(BaoZhenJinActivity.this, GeRenFaDanActivity.class);
                        break;
                    case 3://代理商
                        startactivity(BaoZhenJinActivity.this, DaiLiQiangDanActivity.class);
                        break;
                    case 4://个人抢单
                        startactivity(BaoZhenJinActivity.this, OnePersonQiangDanActivity.class);
                        break;
                    case 5://安装人员
                        startactivity(BaoZhenJinActivity.this, InstallQiangDanActivity.class);
                        break;
                }
                //startactivity(BaoZhenJinActivity.this, DaiLiQiangDanActivity.class);
                finish();
            }
        });

        mBaozhenOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (temp == 1) {
                    ShowToast.showToast("你选择了微信支付");
                    boolean isWeiXin = isWeixinAvilible(BaoZhenJinActivity.this);
                    if(isWeiXin){
                        //微信支付
                        String str = tv_baoZhengJin.getText().toString().trim();
                        String text = str.substring(1);
//                        WeiXInPay(text);
                    }else {
                        ShowToast.showToast("你尚未安装微信");
                    }

                } else if (temp == 2) {
                    ShowToast.showToast("你选择了支付宝支付");
                    boolean bbb = checkAliPayInstalled(BaoZhenJinActivity.this);
                    if(bbb){
                        String str = tv_baoZhengJin.getText().toString().trim();
                        String text = str.substring(1);
                        AliPay(text);
                    }else {
                        ShowToast.showToast("你尚未安装支付宝");
                    }

                }else if(temp == 0){
                    ShowToast.showToast("请选择一种支付方式");
                }
            }
        });

        mBaozhenWeixin.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    temp = 1;
                    mBaozhenZhifubao.setChecked(false);
                }
            }
        });


        mBaozhenZhifubao.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {
                    temp = 2;
                    mBaozhenWeixin.setChecked(false);
                }
            }
        });

    }

    private void getPeiZhiXinXi() {
        MyRequest myRequest = new MyRequest(ConStans.PeiZhiXinXiUrl, RequestMethod.GET);
        CallServer.getInstance().addGet(3, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                try {
                    Log.e("配置信息",json);
                    JSONObject object = new JSONObject(json);
                    if(object.getInt("status") == 1){
                        JSONObject object1 = object.getJSONObject("data");
                        String person_foregift = object1.getString("person_foregift");
                        String company_foregift = object1.getString("company_foregift");
                        int shenfen = Setting.getShenfen();
                        if(shenfen == 1 || shenfen == 3){
                            tv_baoZhengJin.setText("¥" + company_foregift);
                        }else if(shenfen == 2 || shenfen == 4 || shenfen == 5){
                            tv_baoZhengJin.setText("¥" + person_foregift);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, myRequest);
    }

    //微信支付
    private void WeiXInPay(String money) {
        MyRequest myRequest = new MyRequest(ConStans.WeiXinZhiFuUrl, RequestMethod.POST);
        myRequest.add("userid",Setting.getId());
        myRequest.add("total_amount",money);
        myRequest.add("type",1);
        CallServer.getInstance().addGet(3, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                Log.e("微信支付参数",json);
                try {
                    JSONObject object = new JSONObject(json);
                    if(object.getInt("status") == 1){
                        JSONObject object1 = object.getJSONObject("data");
                        req.appId = object1.getString("appid");
                        req.partnerId = object1.getString("partnerid");
                        req.prepayId = object1.getString("prepayid");
                        req.packageValue = object1.getString("package");
                        req.nonceStr = object1.getString("noncestr");
                        req.timeStamp = object1.getString("timestamp");
                        req.sign = object1.getString("sign");
                        sendPayReq();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, myRequest);
    }

    private PayReq req = new PayReq();
    private final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    private final String APP_ID = "wx7dec8b795b8c7bc3";

    /**
     * 调起微信支付
     */
    private void sendPayReq() {
        msgApi.registerApp(APP_ID);
        msgApi.sendReq(req);
        Log.e(">>>>>", req.partnerId);
    }

    //支付宝支付
    private void AliPay(String money) {

        MyRequest myRequest = new MyRequest(ConStans.ZhiFuUrl, RequestMethod.POST);
        myRequest.add("userid",Setting.getId());
        myRequest.add("total_amount",money);
        myRequest.add("type",1);
        CallServer.getInstance().addGet(3, new OnCallBack() {
            @Override
            public void OnSuccess(int what, String json, Object ject) {
                Log.e("支付宝参数",json);
                try {
                    JSONObject object = new JSONObject(json);
                    if(object.getInt("status") == 1){
                        String text = object.getString("data");
                        alipay(text);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, myRequest);
    }


    //去支付宝支付
    public void alipay(final String data) {

        // 完整的符合支付宝参数规范的订单信息

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(BaoZhenJinActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(data);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_CHECK_FLAG = 2;


    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((String) msg.obj);
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {

                        Toast.makeText(BaoZhenJinActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

                        switch (getShenfen()) {
                            case 1://企业
                                startactivity(BaoZhenJinActivity.this, GeRenFaDanActivity.class);
                                break;
                            case 2://个人发单
                                startactivity(BaoZhenJinActivity.this, GeRenFaDanActivity.class);
                                break;
                            case 3://代理商
                                startactivity(BaoZhenJinActivity.this, DaiLiQiangDanActivity.class);
                                break;
                            case 4://个人抢单
                                startactivity(BaoZhenJinActivity.this, OnePersonQiangDanActivity.class);
                                break;
                            case 5://安装人员
                                startactivity(BaoZhenJinActivity.this, InstallQiangDanActivity.class);
                                break;
                        }
                        //startactivity(BaoZhenJinActivity.this, DaiLiQiangDanActivity.class);
                        finish();
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(BaoZhenJinActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(BaoZhenJinActivity.this, "支付失败", Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(BaoZhenJinActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
            }
        }
    };

}
